package control;

import model.GameContext;
import model.GameModel;
import model.stages.StageEnum;
import view.GameUI;
import view.stages.AbstractStage;
import view.stages.StageFactory;

public class ControllerImpl implements ControllerInterface{
	
	private StageFactory stageFactory;
	private GameModel model;
	private GameUI view;
	private AbstractStage currentStage;
	
	
	ControllerImpl(){
		
		model = new GameModel();
		view = new GameUI();
		
		stageFactory = new StageFactory();
		stageFactory.setScreen(view);
		
		currentStage = stageFactory.getStageInstance(GameContext.gameState.getStage().getName());
		view.setStage(currentStage);
		view.setGameState(GameContext.getGameState());
		
		view.setMouseHandler(model.getMouseHandler());
		view.setKeyboardHandler(model.getKeyboardHandler());
		
		currentStage.setModelComponents(model.getStageModel().getModelComponents());
		
		GameContext.setGameModel(model);
	}

	@Override
	public void start() {
		while(isVisible()){
			view.paint();
			update();
			sleep();
		}
	}

	@Override
	public void update() {
		
		model.update();
		view.update();
		
		if(stateChanged()){
			updateStage();
		}
	}
	
	private void updateStage() {
		model.setStageModel(GameContext.getStageModelFactory().getStageModelInstance());
		currentStage = stageFactory.getStageInstance(GameContext.getGameState().getStage().getName());
		
		currentStage.setModelComponents(model.getStageModel().getModelComponents());
		currentStage.setCharacters(model.getStageModel().getCharacters());
		
		view.setStage(currentStage);
		
		view.setMouseHandler(model.getMouseHandler());
		view.setKeyboardHandler(model.getKeyboardHandler());
		
	}
	
	public Boolean stateChanged(){
		return !GameContext.getGameState().getStage().getName().equals(currentStage.getName());
	}

	public Boolean isVisible(){
		return true; //FIXME : arrumar essa POG maldita
	}
	
	public void sleep() {
        try {
            Thread.sleep(25);
        } catch (InterruptedException e) {
        
        }
    }
}
